package com.manage.platform.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.manage.platform.dto.MenuDto;
import com.manage.platform.dto.query.MenuPageQuery;
import com.manage.platform.entity.MenuEntity;
import com.manage.platform.mapper.MenuMapper;
import com.manage.platform.utils.RPage;
import com.manage.platform.utils.TreeListMenuUtil;
import com.manage.platform.vo.CommonVo;
import com.manage.platform.vo.MenuTreeVo;
import com.manage.platform.vo.MenuVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * YWD
 * 2025/9/24
 */
@Slf4j
@AllArgsConstructor
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, MenuEntity> {

    public List<MenuTreeVo> getMenuTree() {
        List<MenuTreeVo> list = this.baseMapper.getMenuTree();
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<MenuTreeVo> newList = BeanUtil.copyToList(list, MenuTreeVo.class);
        return TreeListMenuUtil.buildMenuTreeList(newList);
    }

    public RPage<List<MenuVo>> getMenuPage(MenuPageQuery query) {
        Page<Object> page = PageHelper.startPage(query.getPage(), query.getLimit());
        List<MenuVo> list = this.baseMapper.getMenuPage(query);
        if(CollectionUtils.isEmpty(list)) return null;

        return RPage.ok(list, query.getPage(), query.getLimit(), page.getTotal());
    }

    public MenuVo getMenuDetails(Long id) {
        return BeanUtil.copyProperties(this.getById(id), MenuVo.class);
    }

    public Boolean saveMenu(MenuDto dto) {
        this.baseMapper.saveMenu(dto);
        //默认为管理员配置菜单
        return this.baseMapper.saveRoleMenu(dto.getId(),1L);
    }

    public Boolean updateMenu(MenuDto dto) {
        return updateById(BeanUtil.copyProperties(dto, MenuEntity.class));
    }

    public Boolean deleteMenu(Long id) {
        return removeById(id);
    }

    public Boolean deleteBatchMenu(List<Long> ids) {
        return removeByIds(ids);
    }

    public List<Long> getMenuIdList() {
        LambdaQueryWrapper<MenuEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MenuEntity::getIsDeleted, 0);
        List<MenuEntity> list = list(queryWrapper);
        return list.stream().map(MenuEntity::getId).toList();
    }

    public List<CommonVo> getMenuList(String name) {
        return this.baseMapper.getMenuList(name);
    }


}
